const db = uniCloud.database();

exports.main = async (event, context) => {
  const { data = {} } = event;
  const { dish_id, dish_name, dish_image, dish_price, dish_spiciness, category_id, category_name, uid } = data;

  if (!uid) {
    return {
      code: 401,
      message: '未授权，请先登录',
      data: null
    };
  }

  if (!dish_id) {
    return {
      code: 400,
      message: '菜品ID不能为空',
      data: null
    };
  }

  try {
    const now = new Date();
    
    // 检查是否已经收藏过
    const checkResult = await db.collection('food-favorites')
      .where({
        user_id: uid,
        dish_id: dish_id
      })
      .get();
    
    const existing = checkResult.data && checkResult.data.length > 0 ? checkResult.data[0] : null;

    if (existing) {
      return {
        code: 400,
        message: '该菜品已经被收藏',
        data: null
      };
    }
    
    // 添加收藏
    const result = await db.collection('food-favorites').add({
      user_id: uid,
      dish_id,
      dish_name,
      dish_image,
      dish_price,
      dish_spiciness,
      category_id,
      category_name,
      create_date: now,
      update_date: now
    });
    
    return {
      code: 200,
      message: '收藏成功',
      data: {
        favorite_id: result.id
      }
    };
  } catch (err) {
    return {
      code: 500,
      message: err.message,
      data: null
    };
  }
};
